package org.jeecg.modules.approve.charge.service.impl;

import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.approve.charge.entity.BikeApproveCharge;
import org.jeecg.modules.approve.charge.mapper.BikeApproveChargeMapper;
import org.jeecg.modules.approve.charge.service.IBikeApproveChargeService;
import org.jeecg.modules.approve.charge.vo.BikeApproveChargeRsp;
import org.jeecg.modules.approve.charge.vo.ChargeReq;
import org.jeecg.modules.constant.BikeConstant;
import org.jeecg.modules.param.charge.entity.BikeMemberUserCharge;
import org.jeecg.modules.param.charge.mapper.BikeMemberUserChargeMapper;
import org.jeecg.modules.param.member.entity.BikeMemberChargeReturn;
import org.jeecg.modules.param.member.entity.BikeMemberUser;
import org.jeecg.modules.param.member.mapper.BikeMemberChargeReturnMapper;
import org.jeecg.modules.param.member.mapper.BikeMemberUserMapper;
import org.jeecg.modules.param.refund.entity.BikeMemberUserReturn;
import org.jeecg.modules.utils.AliPayKit;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Description: 余额退款审批信息
 * @Author: jeecg-boot
 * @Date: 2021-11-05
 * @Version: V1.0
 */
@Service
public class BikeApproveChargeServiceImpl extends ServiceImpl<BikeApproveChargeMapper, BikeApproveCharge> implements IBikeApproveChargeService {
    @Resource
    private BikeApproveChargeMapper bikeApproveChargeMapper;
    @Resource
    private BikeMemberUserChargeMapper bikeMemberUserChargeMapper;
    @Resource
    private BikeMemberUserMapper bikeMemberUserMapper;
    @Resource
    private BikeMemberChargeReturnMapper bikeMemberChargeReturnMapper;
    /**
     * 余额退款审批信息列表查询
     */
    @Override
    public IPage<BikeApproveChargeRsp> queryPageList(ChargeReq chargeReq, Integer pageNo, Integer pageSize) {
        Page<BikeApproveChargeRsp> page = new Page<>(pageNo, pageSize);
        IPage<BikeApproveChargeRsp> bikeApproveChargeRspIPage = bikeApproveChargeMapper.queryPageList(page, chargeReq);
        List<BikeApproveChargeRsp> records = bikeApproveChargeRspIPage.getRecords();
        for (BikeApproveChargeRsp tb : records){
            if (tb.getApproveStatus().equals("1")) {
                tb.setApproveYN("1");
            }
            if (tb.getApproveStatus().equals("2")) {
                tb.setApproveYN("0");
            }
        }
        return bikeApproveChargeRspIPage ;
    }

    @Override
    public Result<?> approve(BikeApproveCharge bikeApproveCharge) {
        //获取审批人信息
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //获取审批信息
        BikeApproveCharge approveData = bikeApproveChargeMapper.selectById(bikeApproveCharge.getId());
        //审批账号
        approveData.setHandleBy(sysUser.getUsername());
        //审批时间
        approveData.setHandleTime(new Date());
        //审批理由
        if (StringUtils.isNotEmpty(bikeApproveCharge.getHandleCause())){
            approveData.setHandleCause(bikeApproveCharge.getHandleCause());
        }
        if (bikeApproveCharge.getApproveYN().equals("1")) {
            //同意
            //获取会员信息
            BikeMemberUser memberUser = bikeMemberUserMapper.selectById(approveData.getChargeId());
            memberUser.setBalance(memberUser.getBalance().subtract(approveData.getFreeAmount()));
            //修改用户余额
            bikeMemberUserMapper.updateById(memberUser);
            //修改审批结果
            approveData.setApproveStatus("1");
            //新增余额退款记录
            BikeMemberChargeReturn chargeReturn = new BikeMemberChargeReturn();
            chargeReturn.setUserId(memberUser.getId());
            chargeReturn.setReturnAmount(approveData.getFreeAmount());
            chargeReturn.setBalanceEnd(memberUser.getBalance());
            chargeReturn.setReturnType("1");
            bikeMemberChargeReturnMapper.insert(chargeReturn);
        }else {
            approveData.setApproveStatus("2");
        }
        bikeApproveChargeMapper.updateById(approveData);
        return Result.OK("审批成功");
    }
    /**
     * 审批退款
     * @param bikeApproveCharge 审批记录
     */
    @Override
    public BigDecimal getBalance(BikeApproveCharge bikeApproveCharge) {
        return bikeMemberUserMapper.selectById(bikeApproveCharge.getChargeId()).getBalance();
    }

    /**
     * 审批退款
     * @param bikeApproveCharge 审批记录
     * @param chargeData 充值记录
     */
    private Result<?> refundAli(BikeApproveCharge bikeApproveCharge,BikeMemberUserCharge chargeData) {
        Map<String, String> params = new HashMap<>();
        //支付宝退款编码
        String outRequestNo = UUID.randomUUID().toString();
        //商户订单号
        params.put("outTradeNo",chargeData.getOutTradeNo());
        //退款金额
        params.put("refundAmount",bikeApproveCharge.getFreeAmount().toString());
        //退款原因
        params.put("refundReason",bikeApproveCharge.getApplyCause());
        //退款请求有号
        params.put("outRequestNo",outRequestNo);
        AlipayTradeRefundResponse ali = AliPayKit.refund(params);
        //如果状态码为 10000 则为退款成功
        if (ali.getCode().equals("10000")){
            //获取用户信息
            BikeMemberUser memberUser = bikeMemberUserMapper.selectById(chargeData.getUserId());
            memberUser.setBalance(memberUser.getBalance().subtract(chargeData.getChargeAmount()));
            //修改用户余额
            bikeMemberUserMapper.updateById(memberUser);
            //修改审批结果
            bikeApproveChargeMapper.updateById(bikeApproveCharge);
            chargeData.setIsFullRefund(BikeConstant.y_n_yes);
            bikeMemberUserChargeMapper.updateById(chargeData);
            //新增余额退款记录
            BikeMemberChargeReturn chargeReturn = new BikeMemberChargeReturn();
            chargeReturn.setChargeId(chargeData.getId());
            chargeReturn.setUserId(chargeData.getUserId());
            chargeReturn.setReturnAmount(chargeData.getChargeAmount());
            chargeReturn.setBalanceEnd(memberUser.getBalance());
            chargeReturn.setReturnType("2");
            chargeReturn.setAliOrderId(chargeData.getOutTradeNo());
            chargeReturn.setAliRefundId(outRequestNo);
            bikeMemberChargeReturnMapper.insert(chargeReturn);
            return Result.OK("支付宝退款成功");
        }else{
            return Result.error(Integer.parseInt(ali.getCode()),ali.getMsg());
        }
    }
}
